<!DOCTYPE html>
<html lang="en" color-mode="light">

  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="keywords" content="JavaScript,Hexo" />
  <meta name="author" content="超能虾米" />
  <meta name="description" content="" />
  
  
  <title>
    
      分布式锁的实现 
      
      
      |
    
     超能虾米的博客
  </title>

  
    <link rel="apple-touch-icon" href="/images/favicon.png">
    <link rel="icon" href="/images/favicon.png">
  

  <!-- Raleway-Font -->
  <link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">

  <!-- hexo site css -->
  <link rel="stylesheet" href="/css/main.css" />
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1886449_67xjft27j1l.css" />
  <!-- 代码块风格 -->
  

  <!-- jquery3.3.1 -->
  
    <script defer type="text/javascript" src="/plugins/jquery.min.js"></script>
  

  <!-- fancybox -->
  
    <link href="/plugins/jquery.fancybox.min.css" rel="stylesheet">
    <script defer type="text/javascript" src="/plugins/jquery.fancybox.min.js"></script>
  
  
<script src="/js/fancybox.js"></script>


  

  

  <script>
    var html = document.documentElement
    const colorMode = localStorage.getItem('color-mode')
    if (colorMode) {
      document.documentElement.setAttribute('color-mode', colorMode)
    }
  </script>
<meta name="generator" content="Hexo 5.4.2"><link rel="alternate" href="/atom.xml" title="超能虾米的博客" type="application/atom+xml">
</head>


  <body>
    <div id="app">
      <div class="header">
  <div class="avatar">
    <a href="/">
      <!-- 头像取消懒加载，添加no-lazy -->
      
        <img src="/images/头像.JPEG" alt="">
      
    </a>
    <div class="nickname"><a href="/">超能虾米</a></div>
  </div>
  <div class="navbar">
    <ul>
      
        <li class="nav-item" data-path="/">
          <a href="/">主页</a>
        </li>
      
        <li class="nav-item" data-path="/archives/">
          <a href="/archives/">归档</a>
        </li>
      
        <li class="nav-item" data-path="/categories/">
          <a href="/categories/">分类</a>
        </li>
      
        <li class="nav-item" data-path="/tags/">
          <a href="/tags/">标签</a>
        </li>
      
        <li class="nav-item" data-path="/friends/">
          <a href="/friends/">朋友</a>
        </li>
      
        <li class="nav-item" data-path="/about/">
          <a href="/about/">关于我</a>
        </li>
      
    </ul>
  </div>
</div>


<script src="/js/activeNav.js"></script>



      <div class="flex-container">
        <!-- 文章详情页，展示文章具体内容，url形式：https://yoursite/文章标题/ -->
<!-- 同时为「标签tag」，「朋友friend」，「分类categories」，「关于about」页面的承载页面，具体展示取决于page.type -->


  <!-- LaTex Display -->

  
    <script async type="text/javascript" src="/plugins/mathjax/tex-chtml.js"></script>
  
  <script>
    MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']]
      }
    }
  </script>





  <!-- clipboard -->

  
    <script async type="text/javascript" src="/plugins/clipboard.min.js"></script>
  
  
<script src="/js/codeCopy.js"></script>







  

  

  

  
  <!-- 文章内容页 url形式：https://yoursite/文章标题/ -->
  <div class="container post-details" id="post-details">
    <div class="post-content">
      <div class="post-title">分布式锁的实现</div>
      <div class="post-attach">
        <span class="post-pubtime">
          <i class="iconfont icon-updatetime mr-10" title="Update time"></i>
          2023-05-10 13:52:08
        </span>
        
              <span class="post-categories">
                <i class="iconfont icon-bookmark" title="Categories"></i>
                
                <span class="span--category">
                  <a href="/categories/%E5%90%8E%E7%AB%AF/" title="后端">
                    <b>#</b> 后端
                  </a>
                </span>
                
                <span class="span--category">
                  <a href="/categories/%E5%90%8E%E7%AB%AF/Spring-Cloud/" title="Spring Cloud">
                    <b>#</b> Spring Cloud
                  </a>
                </span>
                
              </span>
          
              <span class="post-tags">
                <i class="iconfont icon-tags mr-10" title="Tags"></i>
                
                <span class="span--tag mr-8">
                  <a href="/tags/%E7%AE%97%E6%B3%95/" title="算法">
                    #算法
                  </a>
                </span>
                
                <span class="span--tag mr-8">
                  <a href="/tags/%E4%B8%AD%E9%97%B4%E4%BB%B6/" title="中间件">
                    #中间件
                  </a>
                </span>
                
              </span>
          
      </div>
      <div class="markdown-body">
        <h2 id="基于-Redis-实现"><a href="#基于-Redis-实现" class="headerlink" title="基于 Redis 实现"></a>基于 Redis 实现</h2><p>相关概念：</p>
<ul>
<li>setnx</li>
<li>lua</li>
<li>redisson</li>
<li>redlock</li>
</ul>
<h3 id="setnx"><a href="#setnx" class="headerlink" title="setnx"></a>setnx</h3><p>目前通常所说的 setnx ( <strong>SET</strong> if <strong>N</strong>ot e<strong>X</strong>ists ) 命令，并非单指 redis 的 setnx key value 这条命令（因为未来 redis 可能要废除 setnx 命令）。<br>一般代指redis中对<strong>set</strong>命令加上<strong>nx</strong>参数进行使用， <strong>set</strong>这个命令，目前已经支持这么多参数可选：<br><code>SET key value [EX seconds|PX milliseconds] [NX|XX] [KEEPTTL]</code><br>其中 <code>EX</code> 和 <code>PX</code> 参数设置过期时间<br><code>NX</code> ：只在键不存在时，才对键进行设置操作。执行 <code>SET key value NX</code> 的效果等同于执行 <code>SETNX key value</code><br><code>XX</code>：只在键已经存在时，才对键进行设置操作。</p>
<blockquote>
<p>在设置分布式锁时，要保证 value 值唯一，通常是<strong>UUID + threadId</strong>，在删除缩时判断 value 是否是当前线程加的锁</p>
</blockquote>
<p>setnx 的方式虽然在加锁的时候可以保证原子性，但是在解锁时要先获取 value 再删除，无法保证原子性，可以用 lua 脚本实现原子性的解锁操作</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- lua删除锁：</span></span><br><span class="line"><span class="comment">-- KEYS和ARGV分别是以集合方式传入的参数，对应上文的Test和uuid。</span></span><br><span class="line"><span class="comment">-- 如果对应的value等于传入的uuid。</span></span><br><span class="line"><span class="keyword">if</span> redis.call(<span class="string">&#x27;get&#x27;</span>, KEYS[<span class="number">1</span>]) == ARGV[<span class="number">1</span>] </span><br><span class="line">    <span class="keyword">then</span> </span><br><span class="line">	<span class="comment">-- 执行删除操作</span></span><br><span class="line">        <span class="keyword">return</span> redis.call(<span class="string">&#x27;del&#x27;</span>, KEYS[<span class="number">1</span>]) </span><br><span class="line">    <span class="keyword">else</span> </span><br><span class="line">	<span class="comment">-- 不成功，返回0</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span> </span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>

<p>使用 setnx 还存在锁续期等问题</p>
<h3 id="redisson"><a href="#redisson" class="headerlink" title="redisson"></a>redisson</h3><p>redisson 中<strong>加锁&#x2F;释放锁</strong>操作都是用<strong>lua</strong>脚本完成的，封装的非常完善，开箱即用。<br>此外，redisson 中通过 <code>watch dog</code> 机制实现了锁续期的功能，锁的可靠性上更加完善。<br>同时，redisson 实现的锁是可重入的。</p>
<h4 id="Watch-dog"><a href="#Watch-dog" class="headerlink" title="Watch dog"></a>Watch dog</h4><p><img src="http://qiniu.c77544s.top/picgo/202210121456281.png" alt="img"><br>redisson 在获取锁的时候，默认的 ttl 是30秒，Watch dog 会每隔10秒看一下，如果还持有锁，将 ttl 续期30s（可以通过修改 Config.lockWatchdogTimeout 来另行指定），从而实现分布式锁的续期。</p>
<ol>
<li>watch dog 在当前节点存活时每10s给分布式锁的key续期 30s；</li>
<li>watch dog 机制启动，且代码中没有释放锁操作时，watch dog 会不断的给锁续期；</li>
<li>从可2得出，如果程序释放锁操作时因为异常没有被执行，那么锁无法被释放，所以释放锁操作一定要放到 finally {} 中；</li>
</ol>
<p>&#x3D;&#x3D;redisson 方案存在的问题：**&#x3D;&#x3D;</p>
<ol>
<li><strong>长时间的 GC pause：</strong> 如果 watch dog 所在服务在续期之前，JVM 进行的 <code>STW</code>，而 <code>STW</code> 的时间又很长，长到超过了锁的过期时间，这样就会出现程序还没有释放锁，但是又会被其他线程锁上。</li>
<li><strong>时钟发生跳跃：</strong> 对于 Redis 服务器如果其时间发生了向跳跃，那么肯定会影响我们锁的过期时间，那么我们的锁过期时间就不是我们预期的了，也会出现 client1和 client2获取到同一把锁，那么也会出现不安全，这个对于 Mysql 也会出现。但是 ZK 由于没有设置过期时间，那么发生跳跃也不会受影响。</li>
<li><strong>长时间的网络 I&#x2F;O</strong>：这个问题和我们的 GC 的 STW 很像，也就是我们这个获取了锁之后我们进行网络调用，其调用时间由可能比我们锁的过期时间都还长，那么也会出现不安全的问题，这个 Mysql 也会有，ZK 也不会出现这个问题。</li>
</ol>
<h3 id="RedLock"><a href="#RedLock" class="headerlink" title="RedLock"></a>RedLock</h3><p>首先 RedLock 的实现需要有 N 个 Redis Master。这些节点<strong>完全互相独立，不存在主从复制或者其他集群协调机制</strong>（RedLock 依赖的环境不能是一个由 N 主 N 从组成的 Cluster 集群模式，因为 Cluster 模式下的各个 Master 并不完全独立，而是存在 Gossip 协调机制的）。之所以要用独立的，是避免了 redis 异步复制造成的锁丢失，比如：主节点没来的及把<strong>刚刚 set 进来这条数据</strong>给从节点，就挂了。<br><img src="http://qiniu.c77544s.top/picgo/202305101419734.png" alt="image.png"></p>
<p>红锁算法认为，只要2N + 1个节点加锁成功，那么就认为获取了锁，解锁时将所有实例解锁。流程为：</p>
<ol>
<li>顺序向五个节点请求加锁</li>
<li>根据一定的<strong>超时时间</strong>来推断是不是跳过该节点</li>
<li>三个节点加锁成功并且花费时间小于锁的有效期</li>
<li>认定加锁成功</li>
</ol>
<blockquote>
<p>Redisson 中已经封装好了 RedLock 的开源实现。</p>
</blockquote>
<p>RedLock 方案相比普通的 Redis 分布式锁方案<strong>可靠性</strong>确实大大提升，但一般业务中只需要一个 Redis Cluster，或者一个 Sentinel，但是这两者都不能承载 RedLock 的落地。</p>
<h2 id="基于数据库实现"><a href="#基于数据库实现" class="headerlink" title="基于数据库实现"></a>基于数据库实现</h2><p>基本原理和 Redis 的 SETNX 类似，其实就是创建一个分布式锁表，加锁后，在表增加一条记录，释放锁即把该数据删掉。<br><img src="http://qiniu.c77544s.top/picgo/202305101439972.png" alt="image.png"></p>
<p><strong>它同样存在一些问题：</strong></p>
<ol>
<li>没有失效时间，容易导致死锁；</li>
<li>依赖数据库的可用性，一旦数据库挂掉，锁就马上不可用；</li>
<li>这把锁只能是非阻塞的，因为数据的 insert 操作，一旦插入失败就会直接报错。没有获得锁的线程并不会进入排队队列，要想再次获得锁就要再次触发获得锁操作；</li>
<li>这把锁是非重入的，同一个线程在没有释放锁之前无法再次获得该锁。因为数据库中数据已经存在了。</li>
</ol>
<ul>
<li>优点:理解起来简单，不需要维护额外的第三方中间件(比如 Redis,Zk)。</li>
<li>缺点:虽然容易理解但是实现起来较为繁琐，需要自己考虑锁超时，加事务等等。性能局限于数据库，一般对比缓存来说性能较低。对于高并发的场景并不是很适合。</li>
</ul>
<h2 id="基于-Zookeeper-的分布式锁"><a href="#基于-Zookeeper-的分布式锁" class="headerlink" title="基于 Zookeeper 的分布式锁"></a>基于 Zookeeper 的分布式锁</h2><p>实现原理为：</p>
<ol>
<li>建立一个节点，假如名为 lock 。节点类型为持久节点（Persistent）</li>
<li>每当进程需要访问共享资源时，会调用分布式锁的 lock() 或 tryLock() 方法获得锁，这个时候会在第一步创建的 lock 节点下建立相应的顺序子节点，节点类型为临时顺序节点（<code>EPHEMERAL_SEQUENTIAL</code>），通过组成特定的名字 name+lock+顺序号。</li>
<li>在建立子节点后，对 lock 下面的所有以 name 开头的子节点进行排序，判断刚刚建立的子节点顺序号是否是最小的节点，假如是最小节点，则获得该锁对资源进行访问。</li>
<li>假如不是该节点，就获得该节点的上一顺序节点，并监测该节点是否存在注册监听事件。同时在这里阻塞，等待监听事件的发生（watcher），获得锁控制权。(这里的watcher其实调用的是object.notifyAll(),用来解除阻塞)。</li>
<li>当调用完共享资源后，调用 unlock() 方法，关闭 ZooKeeper，进而可以引发监听事件，释放该锁。</li>
</ol>
<p><img src="http://qiniu.c77544s.top/picgo/202305101443186.png" alt="image.png"></p>
<ul>
<li>优点: ZK 可以不需要关心锁超时时间，实现起来有现成的第三方包，比较方便，并且支持读写锁，ZK 获取锁会按照加锁的顺序，所以其是公平锁。对于高可用利用 ZK 集群进行保证。</li>
<li>缺点:ZK需要额外维护，增加维护成本，性能和Mysql相差不大，依然比较差。并且需要开发人员了解ZK是什么。</li>
</ul>

      </div>
      
        <div class="prev-or-next">
          <div class="post-foot-next">
            
              <a href="/2023/05/08/%E5%90%8E%E7%AB%AF/Spring%20Boot/Spring%20Boot%20%E5%A6%82%E4%BD%95%E6%8F%90%E9%AB%98%E6%8E%A5%E5%8F%A3%E6%95%B0%E6%8D%AE%E5%AE%89%E5%85%A8%E6%80%A7/" target="_self">
                <i class="iconfont icon-chevronleft"></i>
                <span>Prev</span>
              </a>
            
          </div>
          <div class="post-attach">
            <span class="post-pubtime">
              <i class="iconfont icon-updatetime mr-10" title="Update time"></i>
              2023-05-10 13:52:08
            </span>
            
                  <span class="post-categories">
                    <i class="iconfont icon-bookmark" title="Categories"></i>
                    
                    <span class="span--category">
                      <a href="/categories/%E5%90%8E%E7%AB%AF/" title="后端">
                        <b>#</b> 后端
                      </a>
                    </span>
                    
                    <span class="span--category">
                      <a href="/categories/%E5%90%8E%E7%AB%AF/Spring-Cloud/" title="Spring Cloud">
                        <b>#</b> Spring Cloud
                      </a>
                    </span>
                    
                  </span>
              
                  <span class="post-tags">
                    <i class="iconfont icon-tags mr-10" title="Tags"></i>
                    
                    <span class="span--tag mr-8">
                      <a href="/tags/%E7%AE%97%E6%B3%95/" title="算法">
                        #算法
                      </a>
                    </span>
                    
                    <span class="span--tag mr-8">
                      <a href="/tags/%E4%B8%AD%E9%97%B4%E4%BB%B6/" title="中间件">
                        #中间件
                      </a>
                    </span>
                    
                  </span>
              
          </div>
          <div class="post-foot-prev">
            
              <a href="/2023/05/10/%E5%90%8E%E7%AB%AF/Spring%20Cloud/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/" target="_self">
                <span>Next</span>
                <i class="iconfont icon-chevronright"></i>
              </a>
            
          </div>
        </div>
      
    </div>
    
  <div id="btn-catalog" class="btn-catalog">
    <i class="iconfont icon-catalog"></i>
  </div>
  <div class="post-catalog hidden" id="catalog">
    <div class="title">Contents</div>
    <div class="catalog-content">
      
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E4%BA%8E-Redis-%E5%AE%9E%E7%8E%B0"><span class="toc-text">基于 Redis 实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#setnx"><span class="toc-text">setnx</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#redisson"><span class="toc-text">redisson</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Watch-dog"><span class="toc-text">Watch dog</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RedLock"><span class="toc-text">RedLock</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E4%BA%8E%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AE%9E%E7%8E%B0"><span class="toc-text">基于数据库实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E4%BA%8E-Zookeeper-%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81"><span class="toc-text">基于 Zookeeper 的分布式锁</span></a></li></ol>
      
    </div>
  </div>

  
<script src="/js/catalog.js"></script>




    
      <div class="comments-container">
        




  
    <script async type="text/javascript" src="/plugins/valine.min.js" onload="loadValineSuc(this)"></script>
  

  <div id="vcomments"></div>

  <script>
    function loadValineSuc() {
      new Valine({
        el: '#vcomments',
        appId: 'H2QqshKF8elT2Si5bfKynT9h-9Nh9j0Va',
        appKey: 'WgtVppOWkTZ8fWNReNI1Ymf7',
        placeholder: '有问题请留言吧!',
        avatar: 'retro',
        lang: 'en'
      })
    }
  </script>

    <style>
      .comments-container .v .vempty {
        display: none!important;
      }
    </style>




      </div>
    
  </div>


        
<div class="footer">
  <div class="social">
    <ul>
      
        <li>
          <a title="github" target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">
            <i class="iconfont icon-github"></i>
          </a>
        </li>
      
        <li>
          <a title="email" target="_blank" rel="noopener" href="https://c77544s.github.io/about/">
            <i class="iconfont icon-envelope"></i>
          </a>
        </li>
      
        <li>
          <a title="wechat" target="_blank" rel="noopener" href="https://c77544s.github.io/about/">
            <i class="iconfont icon-wechat"></i>
          </a>
        </li>
      
        <li>
          <a title="rss" href="/atom.xml">
            <i class="iconfont icon-rss"></i>
          </a>
        </li>
      
    </ul>
  </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Copyright © 2023 Oranges</a>
        
    </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Theme by Oranges | Powered by Hexo</a>
        
    </div>
  
  
</div>

      </div>

      <div class="tools-bar">
        <div class="back-to-top tools-bar-item hidden">
  <a href="javascript: void(0)">
    <i class="iconfont icon-chevronup"></i>
  </a>
</div>


<script src="/js/backtotop.js"></script>



        
  <div class="search-icon tools-bar-item" id="search-icon">
    <a href="javascript: void(0)">
      <i class="iconfont icon-search"></i>
    </a>
  </div>

  <div class="search-overlay hidden">
    <div class="search-content" tabindex="0">
      <div class="search-title">
        <span class="search-icon-input">
          <a href="javascript: void(0)">
            <i class="iconfont icon-search"></i>
          </a>
        </span>
        
          <input type="text" class="search-input" id="search-input" placeholder="搜索...">
        
        <span class="search-close-icon" id="search-close-icon">
          <a href="javascript: void(0)">
            <i class="iconfont icon-close"></i>
          </a>
        </span>
      </div>
      <div class="search-result" id="search-result"></div>
    </div>
  </div>

  <script type="text/javascript">
    var inputArea = document.querySelector("#search-input")
    var searchOverlayArea = document.querySelector(".search-overlay")

    inputArea.onclick = function() {
      getSearchFile()
      this.onclick = null
    }

    inputArea.onkeydown = function() {
      if(event.keyCode == 13)
        return false
    }

    function openOrHideSearchContent() {
      let isHidden = searchOverlayArea.classList.contains('hidden')
      if (isHidden) {
        searchOverlayArea.classList.remove('hidden')
        document.body.classList.add('hidden')
        // inputArea.focus()
      } else {
        searchOverlayArea.classList.add('hidden')
        document.body.classList.remove('hidden')
      }
    }

    function blurSearchContent(e) {
      if (e.target === searchOverlayArea) {
        openOrHideSearchContent()
      }
    }

    document.querySelector("#search-icon").addEventListener("click", openOrHideSearchContent, false)
    document.querySelector("#search-close-icon").addEventListener("click", openOrHideSearchContent, false)
    searchOverlayArea.addEventListener("click", blurSearchContent, false)

    var searchFunc = function (path, search_id, content_id) {
      'use strict';
      var $input = document.getElementById(search_id);
      var $resultContent = document.getElementById(content_id);
      $resultContent.innerHTML = "<ul><span class='local-search-empty'>First search, index file loading, please wait...<span></ul>";
      $.ajax({
        // 0x01. load xml file
        url: path,
        dataType: "xml",
        success: function (xmlResponse) {
          // 0x02. parse xml file
          var datas = $("entry", xmlResponse).map(function () {
            return {
              title: $("title", this).text(),
              content: $("content", this).text(),
              url: $("url", this).text()
            };
          }).get();
          $resultContent.innerHTML = "";

          $input.addEventListener('input', function () {
            // 0x03. parse query to keywords list
            var str = '<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length <= 0) {
              return;
            }
            // 0x04. perform local searching
            datas.forEach(function (data) {
              var isMatch = true;
              var content_index = [];
              if (!data.title || data.title.trim() === '') {
                data.title = "Untitled";
              }
              var orig_data_title = data.title.trim();
              var data_title = orig_data_title.toLowerCase();
              var orig_data_content = data.content.trim().replace(/<[^>]+>/g, "");
              var data_content = orig_data_content.toLowerCase();
              var data_url = data.url;
              var index_title = -1;
              var index_content = -1;
              var first_occur = -1;
              // only match artiles with not empty contents
              if (data_content !== '') {
                keywords.forEach(function (keyword, i) {
                  index_title = data_title.indexOf(keyword);
                  index_content = data_content.indexOf(keyword);

                  if (index_title < 0 && index_content < 0) {
                    isMatch = false;
                  } else {
                    if (index_content < 0) {
                      index_content = 0;
                    }
                    if (i == 0) {
                      first_occur = index_content;
                    }
                    // content_index.push({index_content:index_content, keyword_len:keyword_len});
                  }
                });
              } else {
                isMatch = false;
              }
              // 0x05. show search results
              if (isMatch) {
                str += "<li><a href='" + data_url + "' class='search-result-title'>" + orig_data_title + "</a>";
                var content = orig_data_content;
                if (first_occur >= 0) {
                  // cut out 100 characters
                  var start = first_occur - 20;
                  var end = first_occur + 80;

                  if (start < 0) {
                    start = 0;
                  }

                  if (start == 0) {
                    end = 100;
                  }

                  if (end > content.length) {
                    end = content.length;
                  }

                  var match_content = content.substr(start, end);

                  // highlight all keywords
                  keywords.forEach(function (keyword) {
                    var regS = new RegExp(keyword, "gi");
                    match_content = match_content.replace(regS, "<span class=\"search-keyword\">" + keyword + "</span>");
                  });

                  str += "<p class=\"search-result-abstract\">" + match_content + "...</p>"
                }
                str += "</li>";
              }
            });
            str += "</ul>";
            if (str.indexOf('<li>') === -1) {
              return $resultContent.innerHTML = "<ul><span class='local-search-empty'>No result<span></ul>";
            }
            $resultContent.innerHTML = str;
          });
        },
        error: function(xhr, status, error) {
          $resultContent.innerHTML = ""
          if (xhr.status === 404) {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The search.xml file was not found, please refer to：<a href='https://github.com/zchengsite/hexo-theme-oranges#configuration' target='_black'>configuration</a><span></ul>";
          } else {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The request failed, Try to refresh the page or try again later.<span></ul>";
          }
        }
      });
      $(document).on('click', '#search-close-icon', function() {
        $('#search-input').val('');
        $('#search-result').html('');
      });
    }

    var getSearchFile = function() {
        var path = "/search.xml";
        searchFunc(path, 'search-input', 'search-result');
    }
  </script>




        
  <div class="tools-bar-item theme-icon" id="switch-color-scheme">
    <a href="javascript: void(0)">
      <i id="theme-icon" class="iconfont icon-moon"></i>
    </a>
  </div>

  
<script src="/js/colorscheme.js"></script>





        
  
    <div class="share-icon tools-bar-item">
      <a href="javascript: void(0)" id="share-icon">
        <i class="iconfont iconshare"></i>
      </a>
      <div class="share-content hidden">
        
          <a class="share-item" href="https://twitter.com/intent/tweet?text=' + %E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E7%9A%84%E5%AE%9E%E7%8E%B0 + '&url=' + http%3A%2F%2Fc77544s.gitee.io%2F2023%2F05%2F10%2F%25E5%2590%258E%25E7%25AB%25AF%2FSpring%2520Cloud%2F%25E5%2588%2586%25E5%25B8%2583%25E5%25BC%258F%25E9%2594%2581%25E7%259A%2584%25E5%25AE%259E%25E7%258E%25B0%2F + '" target="_blank" title="Twitter">
            <i class="iconfont icon-twitter"></i>
          </a>
        
        
          <a class="share-item" href="https://www.facebook.com/sharer.php?u=http://c77544s.gitee.io/2023/05/10/%E5%90%8E%E7%AB%AF/Spring%20Cloud/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E7%9A%84%E5%AE%9E%E7%8E%B0/" target="_blank" title="Facebook">
            <i class="iconfont icon-facebooksquare"></i>
          </a>
        
      </div>
    </div>
  
  
<script src="/js/shares.js"></script>



      </div>
    </div>
  </body>
</html>
